//
//  AppDelegate.m
//  AntsExpress
//
//  Created by slccper on 16/1/1.
//  Copyright © 2016年 slccper. All rights reserved.
//

#import "AppDelegate.h"
#import "clsOtherFun.h"
#import "MainViewController.h"
#import "CustomNavigation.h"
#import "BPush.h"
#import "VersionCheckController.h"
#import "NewsController.h"
#import "CustomNavigation.h"
#import "clsCheck.h"
#import <BaiduMapAPI_Map/BMKMapComponent.h>
@interface AppDelegate ()
{
    BMKMapManager* _mapManager;
}
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.internetReach = [Reachability reachabilityForInternetConnection];
    [self.internetReach startNotifier];
    if (_IOS8) {
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes: (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound) categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }else{
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
         (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
    }
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(push) name:@"NewPush" object:nil];
    // 在 App 启动时注册百度云推送服务，需要提供 Apikey
    [BPush registerChannel:launchOptions apiKey:[self getUSER][@"BPush"] pushMode:BPushModeProduction withFirstAction:nil withSecondAction:nil withCategory:nil isDebug:YES];
    // App 是用户点击推送消息启动
//    NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
//    if (userInfo) {
//        NSLog(@"从消息启动:%@",userInfo);
//        [BPush handleNotification:userInfo];
//    }
    // Override point for customization after application launch.
    
    //   AK 与bundle id要更换！！！！！！！！！！
    _mapManager = [[BMKMapManager alloc]init];//!!!!!
    BOOL ret = [_mapManager start:[self getUSER][@"BMKMap"] generalDelegate:self];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
//    MainViewController *vc = [[MainViewController alloc]init];
//    CustomNavigation *nav = [[CustomNavigation alloc]initWithRootViewController:vc];
    VersionCheckController *vc = [[VersionCheckController alloc]init];
    self.window.rootViewController = vc;
    [self.window makeKeyAndVisible];
    [UIApplication sharedApplication].applicationIconBadgeNumber=0;
    return YES;
}
- (void)testLocalNotifi
{
    NSLog(@"测试本地通知啦！！！");
    NSDate *fireDate = [[NSDate new] dateByAddingTimeInterval:5];
    [BPush localNotification:fireDate alertBody:@"这是本地通知" badge:3 withFirstAction:@"打开" withSecondAction:@"关闭" userInfo:nil soundName:nil region:nil regionTriggersOnce:YES category:nil];
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [BPush registerDeviceToken:deviceToken];
//    [BPush unbindChannelWithCompleteHandler:^(id result, NSError *error) {
//        if (result) {
//            NSLog(@"%@",result);
//        }
//    }];
    [BPush bindChannelWithCompleteHandler:^(id result, NSError *error) {
        // 需要在绑定成功后进行 settag listtag deletetag unbind 操作否则会失败
        if (result) {
            NSLog(@"%@",result);
            [clsOtherFun setDeviceToken:[result objectForKey:@"channel_id"]];
            [BPush setTag:@"Mytag" withCompleteHandler:^(id result, NSError *error) {
                if (result) {
                    NSLog(@"设置tag成功");
                }
            }];
        }
    }];
}
- (NSDictionary *)getUSER{
    NSDictionary *dic = @{@"com.push.ants":@{@"BPush":@"FDj96FEFY4fs7coq8ComXGaW",@"BMKMap":@"27GHVwGq1Sw90xcn2MLQQzp3"},@"com.ants.p":@{@"BPush":@"x6Rs5ic3r4vi7dyjXnr17T3U",@"BMKMap":@"Hj90wNxDgtwuYwOrO8nHKMpk"}};
    return dic[[NSBundle mainBundle].bundleIdentifier];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"Failed to get token:%@",error);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    // App 收到推送的通知
    
   [UIApplication sharedApplication].applicationIconBadgeNumber=0;
    NSString *str = [userInfo objectForKey:@"type"];
    [clsOtherFun ShowMsg:[userInfo objectForKey:@"type"]];
    if ([userInfo objectForKey:@"type"]) {
        if ([self.window.rootViewController isKindOfClass:[CustomNavigation class]]) {
            [[NSNotificationCenter defaultCenter]postNotificationName:@"NewPush" object:nil];
        }else{
             [[clsCheck sharedManager]setObject:@"new" forKey:@"new"];
        }
    }
    [BPush handleNotification:userInfo];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
{
    [UIApplication sharedApplication].applicationIconBadgeNumber=0;
    NSString *str = [userInfo objectForKey:@"type"];
    if ([userInfo objectForKey:@"type"]) {
        if ([self.window.rootViewController isKindOfClass:[CustomNavigation class]]) {
            [[NSNotificationCenter defaultCenter]postNotificationName:@"NewPush" object:nil];
        }else{
            [[clsCheck sharedManager]setObject:@"new" forKey:@"new"];
        }
    }
    [BPush handleNotification:userInfo];
}
- (void)application:(UIApplication *)application handleActionWithIdentifier:(nullable NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo withResponseInfo:(NSDictionary *)responseInfo completionHandler:(void(^)())completionHandler
{
    [UIApplication sharedApplication].applicationIconBadgeNumber=0;
    NSString *str = [userInfo objectForKey:@"type"];
    if ([userInfo objectForKey:@"type"]) {
        if ([self.window.rootViewController isKindOfClass:[CustomNavigation class]]) {
            [[NSNotificationCenter defaultCenter]postNotificationName:@"NewPush" object:nil];
        }else{
            [[clsCheck sharedManager]setObject:@"new" forKey:@"new"];
        }
        [clsOtherFun ShowMsg:@"new"];
    }
    CustomNavigation *nav = (CustomNavigation *)self.window.rootViewController;
    if ([nav.viewControllers[0]isKindOfClass:[MainViewController class]]) {
        MainViewController *main = (MainViewController *)nav.viewControllers[0];
        [main getUserData];
    }
}
- (void)push
{
    NewsController *news = [[NewsController alloc]initWithNibName:@"NewsController" bundle:nil];
    news.isBack=YES;
    CustomNavigation *nav = (CustomNavigation *)self.window.rootViewController;
    if ([self.window.rootViewController isKindOfClass:[CustomNavigation class]]) {
        [nav pushViewController:news animated:YES];
    }
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    NSLog(@"接收本地通知啦！！！");
    
    [BPush showLocalNotificationAtFront:notification identifierKey:nil];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    return UIInterfaceOrientationMaskPortrait;
}
- (void)onGetNetworkState:(int)iError
{
    if (0 == iError) {
        NSLog(@"联网成功");
    }
    else{
        NSLog(@"onGetNetworkState %d",iError);
    }
    
}

- (void)onGetPermissionState:(int)iError
{
    if (0 == iError) {
        NSLog(@"授权成功");
    }
    else {
        NSLog(@"onGetPermissionState %d",iError);
    }
}


@end
